﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Common.Utilities;
using Common.Utilities.Database;
using Common.Utilities.Dispatcher;

namespace Workflows.Components.Entities.Relations.DirectAssociations
{
    public partial class DbEntityRelationDiscoveryEditor : Form, IComponentEditor
    {
        private object _ActivityNode;
        private DbEntityRelationDiscoveryComponent _ERDiscovery;

        public DbEntityRelationDiscoveryEditor()
        {
            InitializeComponent();
        }

        private void DbEntityRelationDiscoveryEditor_Load(object sender, EventArgs e)
        {
            this.cbo_DbHosts.Items.Clear();
            string[] dbServers = SqlServerEnumUtil.GetAvailableServers();
            if(dbServers !=null && dbServers.Length>0)
            {
                foreach(string dbServer in dbServers)
                {
                    this.cbo_DbHosts.Items.Add(dbServer);
                }
            }
        }

        #region Implementation of IComponentEditor

        public event UpdateComponentSettings UpdateComponentSettingEvent;

        /// <summary></summary>
        public object OwnerActivityNode
        {
            get
            {
                return _ActivityNode;
            }
            set
            {
                _ActivityNode = value;
            }
        }

        /// <summary></summary>
        public Type WorkflowComponentType
        {
            get
            {
                return typeof (DbEntityRelationDiscoveryComponent);
            }
        }

        /// <summary></summary>
        public void LoadSettings(GlobalVariable[] globalVars, WorkflowComponentBase[] fromComponents, object activityNode, WorkflowComponentBase wfComponent)
        {
            this._ActivityNode = activityNode;
            this._ERDiscovery = (DbEntityRelationDiscoveryComponent) wfComponent;

            DbEntityRelationDiscoveryInstruction instruction =
                (DbEntityRelationDiscoveryInstruction) this._ERDiscovery.Instruction;
            string dbServer = DbConnUtil.GetHost(instruction.ConnStr);
            string instanceName = DbConnUtil.GetDbServerInstance(instruction.ConnStr);
            if(!string.IsNullOrEmpty(instanceName))
                dbServer = dbServer + "\\" + instanceName;
            for(int i=0;i<this.cbo_DbHosts.Items.Count;i++)
            {
                if(this.cbo_DbHosts.Items[i].ToString()==dbServer)
                {
                    this.cbo_DbHosts.SelectedIndex = i;
                    break;
                }
            }
            AuthenticationType authType = DbConnUtil.GetAuthenticationType(instruction.ConnStr);
            if(authType==AuthenticationType.WindowsAuthentication)
                this.ck_WindowsAuthentication.Checked = true;
            else
            {
                this.ck_WindowsAuthentication.Checked = false;
                this.txt_UserName.Text = DbConnUtil.GetUserID(instruction.ConnStr);
                this.txt_Password.Text = DbConnUtil.GetPassword(instruction.ConnStr);
            }

            this.PopulateDbs();
            if(this.clb_Dbs.Items.Count>0 && instruction.Databases !=null && instruction.Databases.Count>0)
            {
                for(int i=0;i<this.clb_Dbs.Items.Count;i++)
                {
                    if (instruction.Databases.Contains(this.clb_Dbs.Items[i].ToString()))
                        this.clb_Dbs.SetItemChecked(i, true);
                    else
                        this.clb_Dbs.SetItemChecked(i, false);
                }
            }

            this.ck_InferRelations.Checked = instruction.InferTableRelations;
            this.txt_ResultFilePath.Text = instruction.ResultFilePath;
        }

        /// <summary></summary>
        public void SaveSettings()
        {
            DbEntityRelationDiscoveryInstruction instruction =
               (DbEntityRelationDiscoveryInstruction)this._ERDiscovery.Instruction;
            string dbServer = this.cbo_DbHosts.Text;
            if (this.ck_WindowsAuthentication.Checked)
                instruction.ConnStr = string.Format("server={0};database=master;integrated security=sspi;", dbServer);
            else
                instruction.ConnStr = string.Format(
                    "server={0};database=master;user id={1};password={2};",
                    dbServer, this.txt_UserName.Text, this.txt_Password.Text);
            instruction.Databases=new List<string>();
            for(int i=0;i<this.clb_Dbs.Items.Count;i++)
            {
                if(this.clb_Dbs.GetItemChecked(i))
                    instruction.Databases.Add(this.clb_Dbs.Items[i].ToString());
            }
            instruction.InferTableRelations = this.ck_InferRelations.Checked;
            instruction.ResultFilePath = this.txt_ResultFilePath.Text;
            this._ERDiscovery.Instruction = instruction;
        }

        /// <summary></summary>
        public TestResult Test()
        {
            throw new System.NotImplementedException();
        }

        #endregion

        private void ck_WindowsAuthentication_CheckedChanged(object sender, EventArgs e)
        {
            if(this.ck_WindowsAuthentication.Checked)
            {
                this.txt_UserName.Enabled = false;
                this.txt_Password.Enabled = false;
            }
            else
            {
                this.txt_UserName.Enabled = true;
                this.txt_Password.Enabled = true;
            }
        }

        private void btn_Refresh_Click(object sender, EventArgs e)
        {
            this.PopulateDbs();
        }

        private void PopulateDbs()
        {
            if (this.cbo_DbHosts.SelectedIndex >= 0)
            {
                string connStr = string.Format(
                    "server={0};database={1};integrated security=sspi;",
                    this.cbo_DbHosts.Text, "master");
                if (!this.ck_WindowsAuthentication.Checked)
                {
                    connStr = string.Format(
                        "server={0};database={1};user id={2};password={3}",
                        this.cbo_DbHosts.SelectedItem.ToString(),
                        "master", this.txt_UserName.Text, this.txt_Password.Text);
                }
                this.clb_Dbs.Items.Clear();
                string[] dbNames = DbUtil.GetDatabases(connStr);
                if (dbNames != null && dbNames.Length > 0)
                {
                    foreach (string dbName in dbNames)
                    {
                        this.clb_Dbs.Items.Add(dbName);
                    }
                }
            }
        }

        private void btn_Save_Click(object sender, EventArgs e)
        {
            SaveFileDialog dlg=new SaveFileDialog();
            dlg.Filter = "Result files(*.xml)|*.xml|All files(*.*)|*.*";
            if(dlg.ShowDialog()==System.Windows.Forms.DialogResult.OK)
            {
                this.txt_ResultFilePath.Text = dlg.FileName;
            }
        }

        private void btn_OK_Click(object sender, EventArgs e)
        {
            this.SaveSettings();
            if (this.UpdateComponentSettingEvent != null)
                this.UpdateComponentSettingEvent(this._ActivityNode, this._ERDiscovery);
            this.Close();
        }

        private void btn_Cancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}
